<template>
  <div>
    <div class="inquire-header">
      <div class="input-list">
        <div class="flex align-center gap-1 mb-4" style="align-items: center">
          <div class="list-name">出发时间：</div>
          <el-input v-model="input1" style="width: 240px" placeholder="请输入" />
        </div>
        <div class="flex align-center gap-1 mb-4" style="align-items: center; margin-left: 115px">
          <div class="list-name">出发地点：</div>
          <el-input v-model="input2" style="width: 240px" placeholder="请输入" />
        </div>
        <div class="flex gap-1 mb-4" style="align-items: center; margin-left: 115px">
          <div class="list-name">目的的：</div>
          <el-input v-model="input3" style="width: 240px" placeholder="请输入" />
        </div>
      </div>
      <div class="list-btn" flex>
        <div class="btn-reset" @click="resetSearch">重置</div>
        <!-- <div class="btn-reset" @click="searchData" style="margin-left: 10px">查询</div> -->
      </div>
    </div>
    <div class="inquire-container">
      <div class="inquire-item-header">
        <div class="section">轨迹记录</div>
      </div>
      <div class="covered-table">
        <el-table
          :data="paginatedFilteredData"
          style="width: 100%"
          class="topsoil-tab"
          @selection-change="handleSelectionChange"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column type="selection" width="30" />
          <el-table-column prop="departureTime" label="出发时间" align="center" />
          <el-table-column prop="departureLocation" label="出发地点" align="center" />
          <el-table-column prop="destination" label="目的地" align="center" />
          <el-table-column prop="" label="操作" align="center">
            <template #default="scope">
              <div flex justify-center>
                <div @click="deleteRow(scope.row)" class="btn-details">查看轨迹记录</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            layout="total,sizes,  prev, pager, next, jumper"
            :page-sizes="[9, 18, 27]"
            :total="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="历史轨迹" v-model="dialogVisible" width="1436px" :before-close="handleClose" @opened="initMap">
      <div class="dialog-map">
        <div flex justify-end style="margin-bottom: 10px; align-items: center" @click="startCarTrack">
          <div flex style="align-items: center">
            <div>轨迹播放</div>
            <div class="back-btn" />
          </div>
          <!-- <div @click="pauseCarTrack" value="暂停" style="margin-left: 10px">播放暂停</div>
          <div @click="stopCarTrack" value="结束" style="margin-left: 10px">结束播放</div> -->
          <!-- <input type="button" value="暂停" @click="pauseCarTrack" />
          <input type="button" value="结束" @click="stopCarTrack" /> -->
        </div>

        <div flex justify-end style="margin-bottom: 10px; align-items: center">
          <!-- <input type="button" value="开始" @click="startCarTrack" /> -->
          <input type="button" value="暂停" @click="pauseCarTrack" />
          <input type="button" value="结束" @click="stopCarTrack" style="margin-left: 10px" />
        </div>
        <div ref="mapDiv" class="map-container" />
      </div>
      <div class="dialog-table">
        <div class="table-list">
          <div class="table-title">车牌信息</div>
          <div v-for="(item, index) in ownerInfo" :key="index" class="owner-info">
            <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">{{ item.ownerName }}</div>
            <div>{{ item.licensePlate }}</div>
          </div>
        </div>
        <div class="table-list" style="height: 132px">
          <div class="table-title">车牌信息</div>
          <div v-for="(item, index) in alarmInfo" :key="index" class="owner-info">
            <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px; width: 75px">{{ item.alarmTime }}</div>
            <div>{{ item.alarmLocation }}</div>
          </div>
        </div>
        <div class="table-list" style="height: 131px">
          <div class="table-title">处理信息</div>
          <div class="owner-info">
            <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">处理结果：</div>
            <div>
              <el-radio-group v-model="radio1">
                <el-radio value="1" size="large">真实报警</el-radio>
                <el-radio value="2" size="large">误报</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div flex>
            <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">处理描述：</div>
            <el-input
              v-model="textarea"
              style="width: 240px"
              :rows="2"
              type="textarea"
              placeholder="这是一段文字描述"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, Ref, nextTick, onMounted } from "vue"
import start from "../../../../assets/images/icon-statrt.svg"
import end from "../../../../assets/images/icon-end.svg"
interface User {
  departureTime: string
  departureLocation: string
  destination: string
}
const textarea = ref("")
const input1 = ref("")
const input2 = ref("")
const input3 = ref("")
const radio1 = ref(1)
const ownerInfo = ref([
  {
    ownerName: "车主姓名：",
    licensePlate: "钱浩均"
  },
  {
    ownerName: "车牌号码：",
    licensePlate: "渝CD522Q"
  },
  {
    ownerName: "运输证号：",
    licensePlate: "斯巴鲁"
  },
  {
    ownerName: "车主手机：",
    licensePlate: "15246978726"
  },
  {
    ownerName: "经营区域：",
    licensePlate: "福建省厦门市海沧区"
  },
  {
    ownerName: "从业资格证号：",
    licensePlate: "411520181"
  }
])
const alarmInfo = ref([
  {
    alarmTime: "报警时间：",
    alarmLocation: "2024-09-19 22:38:20"
  },
  {
    alarmTime: "报警地点：",
    alarmLocation: "甘肃省临夏回族自治州康乐县"
  },
  {
    alarmTime: "报警描述：",
    alarmLocation: "作业外出车"
  },
  {
    alarmTime: "报警证据：",
    alarmLocation: "暂未提供证据"
  }
])
// 追踪激活的按钮
const activeBtn = ref<string>("")

const tableData: Ref<User[]> = ref([
  {
    departureTime: "2024-09-21 09:52:38",
    departureLocation: "四川省眉山市",
    destination: "中国石化润滑油公司"
  },
  {
    departureTime: "2024-09-21 08:52:22",
    departureLocation: "四川省眉山市",
    destination: "中国移动通信集团上海有限公司数据业务中心怒江机房"
  },
  {
    departureTime: "2024-09-17 15:42:08",
    departureLocation: "四川省眉山市",
    destination: "上海家化联合股份有限公司(保定路)"
  },
  {
    departureTime: "2024-09-15 16:46:02",
    departureLocation: "四川省眉山市",
    destination: "华润医药(上海)有限公司"
  },
  {
    departureTime: "2024-09-01 17:27:51",
    departureLocation: "四川省眉山市",
    destination: "上海罗氏制药有限公司(龙东大道)"
  },
  {
    departureTime: "2024-09-01 00:01:19",
    departureLocation: "四川省眉山市",
    destination: "上海强生制药有限公司(绿春路)"
  },
  {
    departureTime: "2024-08-26 21:52:09",
    departureLocation: "四川省眉山市",
    destination: "上海汽车集团股份有限公司新能源汽车事业部"
  },
  {
    departureTime: "2024-08-23 05:09:53",
    departureLocation: "四川省眉山市",
    destination: "上海迪蒙幕墙工程技术有限公司(三达路)"
  },
  {
    departureTime: "2024-07-01 19:04:56",
    departureLocation: "四川省眉山市",
    destination: "上海斯可络压缩机有限公司"
  }
])

const multipleSelection = ref<User[]>([])

const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}
// 重置查询
const resetSearch = () => {
  input1.value = ""
  input2.value = ""
  input3.value = ""
  currentPage.value = 1
  activeBtn.value = "reset"
}

// 分页相关的状态
const currentPage = ref(1) // 当前页码
const pageSize = ref(9) // 每页显示条目数

// 根据输入框的内容筛选表格数据
const filteredData = computed(() => {
  const query = input1.value.trim().toLowerCase() // 将输入值转换为小写
  const num = input2.value.trim().toLowerCase() // 车牌号码
  const person = input3.value.trim().toLowerCase() // 围栏名称
  if (!query && !num && !person) {
    return tableData.value // 如果没有输入查询条件，返回全部数据
  }
  return tableData.value.filter(
    (item) =>
      (query && String(item.departureTime).toLowerCase().includes(query)) ||
      (num && String(item.departureLocation).toLowerCase().includes(num)) ||
      (person && String(item.destination).toLowerCase().includes(person))
  )
})

// 根据分页展示过滤后的数据
const paginatedFilteredData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})
// 处理分页变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
}
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}
// 弹窗相关
const dialogVisible = ref(false)
const selectedRow = ref({})

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}
// 删除当前行
const deleteRow = (row: User) => {
  selectedRow.value = row
  dialogVisible.value = true
  // 等待弹窗中的 DOM 元素渲染完成后再初始化地图
  nextTick(() => {
    initMap() // 初始化地图
  })
}

//引入天地图
let map: any
let drivingRoute: any
let _CarTrack: any

const zoom = 14
const startIcon = start
const endIcon = end

const initMap = async () => {
  const T = window.T

  if (!T) {
    console.error("T is not defined. Make sure the TianDiTu SDK is loaded correctly.")
    return
  }

  // 等待 DOM 更新完成
  await nextTick()

  const mapDiv = document.querySelector(".map-container")
  if (!mapDiv) {
    console.error("mapDiv does not exist")
    return
  }

  // 初始化地图
  map = new T.Map(mapDiv, "EPSG:4326")

  // 设置地图中心点和缩放级别
  map.centerAndZoom(new T.LngLat(103.85264, 30.06813), zoom)

  // 添加缩放平移控件
  const control = new T.Control.Zoom()
  map.addControl(control)

  // 调用 Geolocation API 定位当前所在地
  // locateCurrentPosition()

  // 添加驾车路线搜索配置
  const config = {
    policy: 0, // 驾车策略
    onSearchComplete: searchResult // 检索完成后的回调函数
  }

  // 初始化驾车路线搜索服务
  drivingRoute = new T.DrivingRoute(map, config)

  // 执行驾车路线搜索
  searchDrivingRoute()
}

// 定位当前所在地
const locateCurrentPosition = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const currentLng = position.coords.longitude
        const currentLat = position.coords.latitude
        console.log("Current position:", currentLng, currentLat)

        // 将地图中心点设置为当前位置
        map.centerAndZoom(new T.LngLat(currentLng, currentLat), zoom)
      },
      (error) => {
        console.error("Error getting current location:", error)
      },
      {
        enableHighAccuracy: true, // 提高精度
        timeout: 10000, // 超时时间
        maximumAge: 0 // 不使用缓存的位置信息
      }
    )
  } else {
    console.error("Geolocation is not supported by this browser.")
  }
}

// 搜索驾车路线
const searchDrivingRoute = () => {
  map.clearOverLays()

  const startLngLat = new T.LngLat(103.83522, 30.08477)
  const endLngLat = new T.LngLat(103.84964, 30.0578)
  const problematicStart = new T.LngLat(103.84749, 30.07452) // 问题起点
  const problematicEnd = new T.LngLat(103.84865, 30.06074) // 问题终点

  // 驾车路线搜索
  drivingRoute.search(startLngLat, endLngLat)
}

// 创建路线
const createRoute = (lnglats, lineColor = "#059669") => {
  if (!Array.isArray(lnglats) || lnglats.length < 2) {
    console.error("lnglats must be a valid array with at least two points.")
    return
  }

  console.log("Creating CarTrack with coordinates:", lnglats)
  _CarTrack = new T.CarTrack(map, {
    interval: 20,
    speed: 10,
    dynamicLine: true,
    Datas: lnglats,
    polylinestyle: { color: lineColor, width: 6, opacity: 0.9 }
  })

  console.log("CarTrack created:", _CarTrack)
}

// 添加起始点标记
const createStartMarker = (result) => {
  const startMarker = new T.Marker(result.getStart(), {
    icon: new T.Icon({
      iconUrl: startIcon,
      iconSize: new T.Point(44, 34),
      iconAnchor: new T.Point(12, 31)
    })
  })
  map.addOverLay(startMarker)

  const endMarker = new T.Marker(result.getEnd(), {
    icon: new T.Icon({
      iconUrl: endIcon,
      iconSize: new T.Point(44, 34),
      iconAnchor: new T.Point(12, 31)
    })
  })
  map.addOverLay(endMarker)
}

// 路线搜索完成的回调
const searchResult = (result) => {
  createStartMarker(result)

  const routes = result.getNumPlans()
  for (let i = 0; i < routes; i++) {
    const plan = result.getPlan(i)
    // 创建原有路线
    const path = plan.getPath()
    createRoute(path)

    // 在原有线路的基础上，添加问题红色线路
    addProblematicRoute(path, new T.LngLat(103.84749, 30.07452), new T.LngLat(103.84865, 30.06074))
  }
}

// 创建问题线路
const addProblematicRoute = (originalPath, problematicStart, problematicEnd) => {
  // 查找原有路径中，问题起点和终点的索引
  const startIndex = originalPath.findIndex(
    (point) => point.lng === problematicStart.lng && point.lat === problematicStart.lat
  )
  const endIndex = originalPath.findIndex(
    (point) => point.lng === problematicEnd.lng && point.lat === problematicEnd.lat
  )

  if (startIndex === -1 || endIndex === -1 || startIndex > endIndex) {
    console.error("Invalid problematic segment.")
    return
  }

  // 获取红色线路的起点和终点之间的所有点
  const problematicSegment = originalPath.slice(startIndex, endIndex + 1)

  // 创建红色线路
  createRoute(problematicSegment, "red")

  // 在问题线路的起点和终点添加标记
  addMarker(problematicStart, "问题起点")
  addMarker(problematicEnd, "问题终点")
}

// 添加标记的函数
const addMarker = (lngLat, info) => {
  const marker = new T.Marker(lngLat, {
    icon: new T.Icon({
      iconUrl: "your_icon_url.png", // 这里可以放置信息图标的URL
      iconSize: new T.Point(20, 20),
      iconAnchor: new T.Point(10, 10)
    })
  })

  // 点击事件展示问题信息
  marker.addEventListener("click", () => {
    alert(`问题信息: ${info}`) // 替换为实际展示逻辑
  })

  map.addOverLay(marker)
}

// 控制按钮函数
const startCarTrack = () => _CarTrack?.start()
const pauseCarTrack = () => _CarTrack?.pause()
const stopCarTrack = () => _CarTrack?.stop()
</script>
<style lang="scss" scoped>
@import "@/styles/global.scss";
.app-container {
  width: 100%;
  height: 100%;
  position: relative;
  .inquire-header {
    width: 100%;
    height: 78px;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    border: 1px solid #e4e4e7;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 23px 23px;
    .input-list {
      display: flex;
      align-items: center;
      margin-top: 16px;

      .list-name {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85) !important;
        margin-bottom: 6px;
      }
    }
    .list-btn {
      // width: 140px;
      // display: flex;
      // justify-content: space-between;
      // align-items: center;
      cursor: pointer;

      .btn-reset {
        width: 64px;
        height: 31px;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #d9d9d9;
        text-align: center;
        line-height: 31px;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
      }
      .btn-reset:hover {
        background-color: #059669; // 激活状态背景颜色
        color: #fff; // 激活状态的字体颜色
      }

      .active {
        background-color: #059669; // 激活状态背景颜色
        color: #fff; // 激活状态的字体颜色
      }
    }
  }
  .inquire-container {
    width: 100%;
    height: 91%;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    margin: 16px 0 20px 0;
    padding: 20px 23px;
    .inquire-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .section {
      font-family: AlibabaPuHuiTi20;
      font-weight: bold;
      font-size: 16px;
      color: #000000;
    }
    .input-btn {
      width: 82px;
      height: 32px;
      background: #059669;
      border-radius: 0px 0px 0px 0px;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 14px;
      cursor: pointer;
      span {
        margin-left: 4px;
      }
    }
  }
  .covered-table {
    width: 100%;
    position: relative;
    .demo-pagination-block {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
    }
    .details-content {
      height: 330px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-top: 10px;
      .details-item {
        display: flex;
        .details-text {
          width: 100px;
          text-align: right;
          margin-right: 15px;
        }
      }
    }
  }

  .dialog-map {
    cursor: pointer;
    .back-btn {
      width: 22px;
      height: 22px;
      background-image: url("../../../../assets/images/icon-bo.png");
      background-size: 100% 100%;
      background-repeat: no-repeat; /* 防止图片重复 */
      margin-left: 5px;
    }
  }
  .dialog-table {
    width: 50%;
    height: 589px;
    margin-left: 38px;

    .table-list {
      width: 334px;
      height: 188px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-bottom: 59px;
      .table-title {
        font-family: AlibabaPuHuiTi20;
        font-weight: 600;
        font-size: 14px;
        color: #000000;
        margin-bottom: 8px;
      }
      .owner-info {
        display: flex;
        align-items: center;
      }
    }
  }
  .map-container {
    width: 1018px;
    height: 708px;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #e4e4e7;
  }
}
::v-deep .el-dialog__body {
  display: flex;
  align-items: center;
}
</style>
